package com.qdxwx.manage.controller.course;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.page.TableDataInfo;
import com.qdxwx.common.utils.BaJiaYunUtils;
import com.qdxwx.common.utils.HttpUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.course.CourseNodeService;
import com.qdxwx.data.service.website.WebsiteProfileService;

import com.qdxwx.manage.controller.BaseController;
import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.course.CourseNode;
import com.qdxwx.models.enums.WebsiteProfileType;
import com.qdxwx.models.live.LiveBaiJiaYun;
import com.qdxwx.models.manager.Manager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 知识点的基本信息Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/course/node/live")
public class CourseNodeLiveController extends BaseController {

    @Autowired
    private WebsiteProfileService websiteProfileService;

    @Autowired
    private CourseNodeService courseNodeService;

    @GetMapping("/list.html")
    public String list() { return "course/node-live-list"; }

    /**
     * 查询我的直播列表
     */
    @PostMapping("/list.json")
    @ResponseBody
    public TableDataInfo list(HttpServletRequest request) {
        String name = request.getParameter("name");
        CourseNode courseNode = new CourseNode();
        courseNode.setName(name);
        courseNode.setFileType("LIVE");
        List<CourseNode> list = courseNodeService.getList(courseNode, PageRequest.form(request));
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(courseNodeService.count(courseNode));
        return rspData;
    }


    @GetMapping("/add.html")
    public String add() {
        return "course/node-live-add";
    }

    @GetMapping("/edit.html")
    public String edit(HttpServletRequest request, ModelMap mmap) {
        String roomId = request.getParameter("roomId");
        if (TKString.isEmpty(roomId)) return error404;
        Map<String, Object> baiJiaYun = websiteProfileService.getMap(WebsiteProfileType.baiJiaYun.toString());
        SortedMap<String, String> message = new TreeMap<>();
        message.put("room_id", roomId);
        message.put("timestamp", new Date().getTime() / 1000 + "");
        message.put("sign", BaJiaYunUtils.createSign(message, baiJiaYun));
        String roomMsg = HttpUtils.doPost(baiJiaYun.get("partnerDomain") + "openapi/room/info", message);
        JSONObject room = JSON.parseObject(roomMsg);
        if (TKConvert.toInteger(room.get("code").toString()) == 0) {
            mmap.put("roomData", room.get("data"));
        }
        return "course/node-live-edit";
    }

    /**
     * 添加vid_live_room
     */
    @RequestMapping("/add.json")
    @ResponseBody
    public AjaxResult add(HttpServletRequest request) {
        String roomTitle = request.getParameter("roomTitle");
        if(TKString.isEmpty(roomTitle)) return AjaxResult.error("房间名称不能为空");
        LiveBaiJiaYun liveRoom = new LiveBaiJiaYun();
        liveRoom.setRoomTitle(roomTitle);
        liveRoom.setMaxUsers(TKConvert.toInteger(request.getParameter("maxUsers"),10));
        liveRoom.setStartTime(TKConvert.toLocalDateTime(request.getParameter("startTime"),LocalDateTime.now()));
        liveRoom.setEndTime(TKConvert.toLocalDateTime(request.getParameter("endTime"),LocalDateTime.now()));
        liveRoom.setType(TKConvert.toInteger(request.getParameter("type"),2));
        return BaiJiaYunAdd(liveRoom);
    }

    /**
     * 更新live_room
     */
    @RequestMapping("/edit.json")
    @ResponseBody
    public AjaxResult edit(HttpServletRequest request) {
        String roomId = request.getParameter("roomId");
        if(TKString.isEmpty(roomId)) return AjaxResult.error("房间ID为空");
        String roomTitle = request.getParameter("roomTitle");
        if(TKString.isEmpty(roomTitle)) return AjaxResult.error("房间名称不能为空");
        LiveBaiJiaYun liveRoom = new LiveBaiJiaYun();
        liveRoom.setRoomId(roomId);
        liveRoom.setRoomTitle(roomTitle);
        liveRoom.setMaxUsers(TKConvert.toInteger(request.getParameter("maxUsers"),10));
        liveRoom.setStartTime(TKConvert.toLocalDateTime(request.getParameter("startTime"),LocalDateTime.now()));
        liveRoom.setEndTime(TKConvert.toLocalDateTime(request.getParameter("endTime"),LocalDateTime.now()));
        liveRoom.setType(TKConvert.toInteger(request.getParameter("type"),2));
        return BaiJiaYunEdit(liveRoom);
    }

    /**
     * 百家云直播间操作
     */
    public AjaxResult BaiJiaYunAdd(LiveBaiJiaYun room) {
        Map<String, Object> mmap = websiteProfileService.getMap(WebsiteProfileType.baiJiaYun.toString());
        if (TKString.isEmpty(room.getRoomTitle())) {
            return AjaxResult.error("直播间名称不能为空");
        }
        LocalDateTime startDate = room.getStartTime();
        if (startDate == null) {
            return AjaxResult.error("请选择直播开始时间");
        }
        LocalDateTime endDate = room.getEndTime();
        if (endDate == null) {
            return AjaxResult.error("请选择直播结束时间");
        }
        long startTime = startDate.toEpochSecond(ZoneOffset.of("+8"));
        long endTime = endDate.toEpochSecond(ZoneOffset.of("+8"));
        long createTime = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        SortedMap<String, String> message = new TreeMap<>();
        message.put("end_time", endTime + "");
        message.put("max_users", room.getMaxUsers() + "");
        message.put("start_time", startTime + "");
        message.put("timestamp", createTime + "");
        message.put("title", room.getRoomTitle());
        message.put("type", room.getType() + "");
        message.put("sign", BaJiaYunUtils.createSign(message, mmap));
        String roomMsg = HttpUtils.doPost(mmap.get("partnerDomain") + "openapi/room/create", message);
        Map ruet = JSON.parseObject(roomMsg, Map.class);
        int code = TKConvert.toInteger(ruet.get("code").toString(), 1);
        if (code == 0) {
            Map roomData = JSON.parseObject(ruet.get("data").toString(), Map.class);
            return AjaxResult.success(roomData.get("room_id").toString());
        } else {
            return AjaxResult.error(ruet.get("msg").toString());
        }
    }

    /*
     * 更新直播间操作
     */
    public AjaxResult BaiJiaYunEdit(LiveBaiJiaYun room) {

        if (TKString.isEmpty(room.getRoomId())) {
            return AjaxResult.error("房间号不存在");
        }
        if (TKString.isEmpty(room.getRoomTitle())) {
            return AjaxResult.error("直播间名称不能为空");
        }
        LocalDateTime startDate = room.getStartTime();
        if (startDate == null) {
            return AjaxResult.error("请选择直播开始时间");
        }
        LocalDateTime endDate = room.getEndTime();
        if (endDate == null) {
            return AjaxResult.error("请选择直播结束时间");
        }
        long startTime = startDate.toEpochSecond(ZoneOffset.of("+8"));
        long endTime = endDate.toEpochSecond(ZoneOffset.of("+8"));
        long createTime = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        Map<String, Object> mmap = websiteProfileService.getMap(WebsiteProfileType.baiJiaYun.toString());
        SortedMap<String, String> message = new TreeMap<>();
        message.put("end_time", endTime + "");
        message.put("room_id", room.getRoomId());
        message.put("max_users", room.getMaxUsers() + "");
        message.put("start_time", startTime + "");
        message.put("timestamp", createTime + "");
        message.put("title", room.getRoomTitle());
        message.put("sign", BaJiaYunUtils.createSign(message, mmap));
        String roomMsg = HttpUtils.doPost(mmap.get("partnerDomain") + "openapi/room/update", message);
        Map ruet = JSON.parseObject(roomMsg, Map.class);
        int code = TKConvert.toInteger(ruet.get("code").toString(), 1);
        if (code == 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error(ruet.get("msg").toString());
    }

    /**
     * 进入直播间
     */
    @RequestMapping("/into.json")
    @ResponseBody
    public AjaxResult toLiveRoom(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if(manager == null) return AjaxResult.error("登录超时");
        String roomId = request.getParameter("id");
        if (TKString.isEmpty(roomId)) {
            return AjaxResult.error("房间号不存在");
        }
        //默认以助教身份进入直播间
        int role = TKConvert.toInteger(request.getParameter("role"), 2);
        String type = request.getParameter("type");
        if (TKString.isEmpty(type)) {
            type = "WEB";
        }
        Map<String,Object> baijiayunMap = websiteProfileService.getMap(WebsiteProfileType.baiJiaYun.toString());
        SortedMap<String, String> map = new TreeMap<>();
        try {
            map.put("room_id", roomId);
            map.put("manager_number", manager.getManagerId() + "");
            map.put("manager_name", manager.getManagerName());
            map.put("user_role", role + "");
            String sign = BaJiaYunUtils.createSign(map, baijiayunMap);
            String retMsg = "";
            if ("WEB".equals(type)) {//PC端打开直播
                retMsg = baijiayunMap.get("partnerDomain") + "web/room/enter?" + BaJiaYunUtils.mapToString(map, sign);
            } else if ("APP".equals(type)) {//客户端打开直播
                retMsg = baijiayunMap.get("partnerDomain") + "web/room/enter?" + BaJiaYunUtils.mapToString(map, sign);
                retMsg = URLEncoder.encode(retMsg, StandardCharsets.UTF_8);
                retMsg = "baijiacloud://urlpath=" + retMsg + "&token=token&ts=ts";
            }
            return AjaxResult.success(retMsg);
        } catch (Exception e) {
            return AjaxResult.error("获取直播地址失败");
        }
    }
}
